package com.wuwei.tms.setting.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.tms.pojo.Borrow;
import com.wuwei.tms.pojo.User;
import com.wuwei.tms.setting.mapper.UserMapper;
import com.wuwei.tms.setting.service.UserService;
import com.wuwei.tms.utils.result.Result;
import com.wuwei.tms.workbench.mapper.BorrowMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    private UserMapper userMapper;

    @Resource
    private BorrowMapper borrowMapper;




//    /**
//     * 销毁账户的时候先要判断该用户有没有还没还的工具，如果有没还的工具不能销毁该用户
//     * @param id
//     * @return
//     */
//    @Override
//    public Message delete(String id) {
//        Message message = new Message();
//        message.setSuccess(true);
//
//        //先查询该用户有没有借过工具，如果借过工具，则不能销毁账号
//        List<Borrow> borrows = borrowMapper.getUnReturnByBorrowId(id);
//        if (borrows.size() != 0) {
//            message.setSuccess(false);
//            message.setMessage("销毁失败！您还有工具没有还！");
//            throw new DeleteException("销毁失败！您还有工具没有还！");
//        }
//
//        int i = userMapper.delete(id);
//        if (i != 1) {
//            message.setSuccess(false);
//            message.setMessage("修改密码失败！");
//            throw new DeleteException("修改密码失败！");
//        }
//
//        return message;
//    }

    @Override
    public Result<String> setPassword(User user, Long empno, String newPassword) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(empno!=null,User::getEmpno,empno);
        user.setEmpno(empno);
        user.setPassword(newPassword);
        int update = userMapper.update(user, updateWrapper);
        if (update!=1) {
            return Result.fail("密码修改失败！数据库修改失败");
        }
        return Result.ok("密码修改成功！");
    }

    /**
     * 删除用户前要检查一下该用户有无未归还的工具
     * @param id
     */
    @Override
    public  Result<String>  deleteById(Long id) {
        User user = userMapper.selectById(id);
        Long empno = user.getEmpno();
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Borrow::getBorrowById,empno).eq(Borrow::getReturnFlag,0);
        List<Borrow> borrowList = borrowMapper.selectList(queryWrapper);
        if (borrowList.size()>0) {
            return Result.fail("删除失败，该员工有工具未归还！");
        } else {
            userMapper.deleteById(id);
            return Result.ok("删除成功！");
        }

    }

}
